package com.wen.common.interceptor.impl;

import cn.hutool.core.util.StrUtil;
import com.wen.common.exception.CustomException;
import com.wen.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 */
@Slf4j
@Component
public class TestInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    //方法执行前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 跨域
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");

        System.out.println("方法" + request.getMethod() + "被拦截了...");

        String jwt = request.getHeader("token");
        System.out.println("拦截器拦截jwt ：" + jwt);

        if (StrUtil.isBlank(jwt)) {
            System.out.println("jwt = null");
            throw new CustomException("4002", "未获取到token, 请重新登录");
        }
        // 校验jwt
        Claims claim = jwtUtil.getClaimByJwt(jwt);
        if (claim == null || jwtUtil.isExpired(claim.getExpiration())) {
            System.out.println("claim = null");
            throw new CustomException("4001", "token已过期, 请重新登录");
        }

        return true;
    }

    //方法执行后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("方法拦截后...");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    //流程结束后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("流程结束后...");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
